package main

import (
	"am-dingtalk-webhook/model"
	"am-dingtalk-webhook/notifier"
	"flag"
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
)

var (
	h                   bool
	defaultRobot        string
	robotType           string
	Secret              string
	Env                 string
	Port                int
	includeSeverities   string
	includeSeverityList []string
	atAll               bool
)

func init() {
	// 使用方法 ./webhook -h
	flag.BoolVar(&h, "h", false, "help")
	flag.StringVar(&defaultRobot, "defaultRobot", "", "global dingtalk robot webhook, you can overwrite by alert rule with annotations dingtalkRobot")
	flag.StringVar(&robotType, "robotType", "keywords", "钉钉机器人类型，枚举：sign/keywords")
	flag.StringVar(&Secret, "secret", "", "如果机器人使用加签方式，这里填写密钥")
	flag.StringVar(&Env, "env", "默认环境", "告警标题显示所属的业务环境线")
	flag.IntVar(&Port, "port", 8888, "服务端口")
	flag.StringVar(&includeSeverities, "includeSeverities", "", "发送严重等级列表，多个用逗号隔开，不填则默认发送全部。示例：\"critical,严重\"")
	flag.BoolVar(&atAll, "atAll", false, "钉钉消息是否At所有人")

}

func main() {

	// 解析启动参数
	flag.Parse()
	if h {
		flag.Usage()
		return
	}

	// 解析flag参数：严重性文本，为一个列表
	if includeSeverities != "" {
		includeSeverityList = strings.Split(includeSeverities, ",")
		fmt.Printf("只将以下严重等级的告警发送至钉钉: %+v\n", includeSeverityList)
	}

	// 解析flag参数，钉钉消息是否at所有人
	// Use the flag
	if atAll {
		fmt.Println("atAll mode enabled")
	} else {
		fmt.Println("atAll mode disabled")
	}

	// 初始化
	r := gin.Default()

	// 定义API：健康检查接口
	r.GET("/healthz", func(c *gin.Context) { //路由
		c.JSON(200, gin.H{
			"message": "yes",
		})
	})

	// 定义API：暴露给alertmanager的webhook，用接受发送过来的告警信息
	r.POST("/webhook", func(c *gin.Context) {
		var notification model.Notification

		err := c.BindJSON(&notification)
		if err != nil {
			c.JSON(400, gin.H{"error": err.Error()})
			return
		}
		// 打印接口获取到的json转化后的结构体
		fmt.Printf("%+v\n", notification)

		// 钉钉机器人使用关键字类型
		if robotType == "keywords" {
			notifier.SendWithKeywords(notification, defaultRobot, Env, includeSeverityList, atAll)
			c.JSON(200, gin.H{
				"message": "钉钉机器人（关键字）消息发送成功！",
			})
			// 钉钉机器人使用"加签"类型
		} else if robotType == "sign" {
			notifier.SendWithSign(notification, defaultRobot, Secret, Env, includeSeverityList, atAll)
			c.JSON(200, gin.H{
				"message": "钉钉机器人（加签）消息发送成功！",
			})
		}
	})

	// 指定端口启动
	p := fmt.Sprintf(":%d", Port)
	r.Run(p)
}
